/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package me.weyye.hipermission;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.TableLayoutManager;
import ohos.agp.components.Text;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.BlendMode;
import ohos.agp.render.ColorMatrix;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.WrongTypeException;
import ohos.global.resource.solidxml.Pattern;
import ohos.global.resource.solidxml.TypedAttribute;

import java.io.IOException;
import java.util.HashMap;

/**
 * 自定义权限申请弹窗
 *
 * @since 2021-04-12
 */
public class PermissionDialog extends CommonDialog {
    private static final int COLUMN_COUNT = 3;
    private Context mContext;

    private Text mTvTitle;
    private Text mTvDesc;
    private Button mBtnNext;
    private ListContainer mGvPermission;
    private DirectionalLayout mLlRoot;

    /**
     * PermissionDialog
     *
     * @param context 上下文
     */
    public PermissionDialog(Context context) {
        super(context);
        mContext = context;
        setTransparent(true);
        setAlignment(LayoutAlignment.CENTER);
        Component contentView = LayoutScatter.getInstance(mContext)
                .parse(ResourceTable.Layout_dialog_request_permission, null, true);
        setContentCustomComponent(contentView);
        initView();
    }

    private void initView() {
        Component component = getContentCustomComponent();
        mTvTitle = (Text) component.findComponentById(ResourceTable.Id_tvTitle);
        mLlRoot = (DirectionalLayout) component.findComponentById(ResourceTable.Id_llRoot);
        mTvDesc = (Text) component.findComponentById(ResourceTable.Id_tvDesc);
        mBtnNext = (Button) component.findComponentById(ResourceTable.Id_goto_settings);
        mGvPermission = (ListContainer) component.findComponentById(ResourceTable.Id_gvPermission);
    }

    /**
     * 设置Provider
     *
     * @param provider
     */
    public void setItemProvider(BaseItemProvider provider) {
        mGvPermission.setItemProvider(provider);
        TableLayoutManager tableLayoutManager = new TableLayoutManager();
        tableLayoutManager.setColumnCount(COLUMN_COUNT);
        mGvPermission.setLayoutManager(tableLayoutManager);
    }

    /**
     * 设置标题
     *
     * @param title 标题
     */
    public void setTitle(String title) {
        mTvTitle.setText(title);
    }

    /**
     * 设置内容
     *
     * @param msg 内容
     */
    public void setMsg(String msg) {
        mTvDesc.setText(msg);
    }

    /**
     * 设置按钮监听
     *
     * @param listener 监听器
     */
    public void setBtnOnClickListener(Component.ClickedListener listener) {
        mBtnNext.setClickedListener(listener);
    }

    /**
     * 设置风格
     *
     * @param styleId 风格id
     */
    public void setStyleId(int styleId) {
        if (styleId == 0) {
            return;
        }
        int msgColor = 0;
        int titleColor = 0;
        int itemTextColor = 0;
        int btnTextColor = 0;
        int bgFilterColor = 0;
        int iconFilterColor = 0;
        int background = 0;
        int btnBackground = 0;
        Resource backgroundRes = null;
        Resource btnBackgroundRes = null;
        try {
            Pattern pattern = mContext.getResourceManager().getElement(styleId).getPattern();
            HashMap<String, TypedAttribute> patternHash = pattern.getPatternHash();
            for (String key : patternHash.keySet()) {
                TypedAttribute typedAttribute = patternHash.get(key);
                if (typedAttribute != null) {
                    switch (key) {
                        case "PermissionMsgColor":
                            msgColor = typedAttribute.getColorValue();
                            break;
                        case "PermissionTitleColor":
                            titleColor = typedAttribute.getColorValue();
                            break;
                        case "PermissionItemTextColor":
                            itemTextColor = typedAttribute.getColorValue();
                            break;
                        case "PermissionButtonTextColor":
                            btnTextColor = typedAttribute.getColorValue();
                            break;
                        case "PermissionBackround":
                            background = typedAttribute.getResId();
                            if (background == 0) {
                                backgroundRes = typedAttribute.getMediaResource();
                            }
                            break;
                        case "PermissionButtonBackground":
                            btnBackground = typedAttribute.getResId();
                            if (btnBackground == 0) {
                                btnBackgroundRes = typedAttribute.getMediaResource();
                            }
                            break;
                        case "PermissionBgFilterColor":
                            bgFilterColor = typedAttribute.getColorValue();
                            break;
                        case "PermissionIconFilterColor":
                            iconFilterColor = typedAttribute.getColorValue();
                            break;
                        default:
                            break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        if (titleColor != 0) {
            mTvTitle.setTextColor(new Color(titleColor));
        }

        if (background != 0) {
            mLlRoot.setBackground(new ShapeElement(mContext, background));
        } else if (backgroundRes != null) {
            PixelMapElement element = new PixelMapElement(backgroundRes);
            element.setColorMatrix(new ColorMatrix(new float[]{
                    1, 0, 0, 0, RgbColor.fromArgbInt(bgFilterColor).getRed(),// 红色值
                    0, 1, 0, 0, RgbColor.fromArgbInt(bgFilterColor).getGreen(),// 绿色值
                    0, 0, 1, 0, RgbColor.fromArgbInt(bgFilterColor).getBlue(),// 蓝色值
                    0, 0, 0, 1, 1 // 透明度
            }));
            element.setStateColorMode(BlendMode.LIGHTEN);
            mLlRoot.setBackground(element);
        }
        if (msgColor != 0) {
            mTvDesc.setTextColor(new Color(msgColor));
        }
        if (itemTextColor != 0) {
            ((PermissionItemProvider) mGvPermission.getItemProvider()).setTextColor(itemTextColor);
        }
        if (btnBackground != 0) {
            mBtnNext.setBackground(new ShapeElement(mContext, btnBackground));
        } else if (btnBackgroundRes != null) {
            mBtnNext.setBackground(new PixelMapElement(btnBackgroundRes));
        }
        if (btnTextColor != 0) {
            mBtnNext.setTextColor(new Color(btnTextColor));
        }
        if (iconFilterColor != 0) {
            setFilterColor(iconFilterColor);
        }
    }

    /**
     * 设置图标颜色
     *
     * @param color 颜色值
     */
    public void setFilterColor(int color) {
        if (color == 0) {
            return;
        }
        ((PermissionItemProvider) mGvPermission.getItemProvider()).setFilterColor(color);
    }
}
